package com.block.product.service.union;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.service.LogFactory;
import com.block.product.model.dto.UniLoginDTO;
import com.block.product.model.param.ProdApiInfoParam;
import com.block.product.model.result.UnionLoginResult;
import com.block.product.service.IUnionLoginService;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Service
public class YiCheHangUnionLoginService implements IUnionLoginService {

    private static final Logger log = LogFactory.getProductUniLog();
    private static final String AES_CBC = "AES/CBC/PKCS5Padding";

    @Override
    public UnionLoginResult checkUser(UniLoginDTO uniLoginDTO, ProdApiInfoParam apiInfoParam) {
        UnionLoginResult loginResult = new UnionLoginResult();
        loginResult.setSuccess(true);
        return loginResult;
    }

    @Override
    public UnionLoginResult loginUser(UniLoginDTO uniLoginDTO, ProdApiInfoParam apiInfoParam,String resultInfo) {

        UnionLoginResult loginResult = new UnionLoginResult();
        loginResult.setSuccess(false);

        String checkUrl = apiInfoParam.getLoginUrl();
        String mobile = uniLoginDTO.getMobile();


        Map<String, Object> bizmMap = new HashMap<>();
        bizmMap.put("mobile", mobile);
        bizmMap.put("appId", apiInfoParam.getApiCode());
        String vi = "D5A89LDd5h8g4sgU";
        String sign = encrypt(JSON.toJSONString(bizmMap), apiInfoParam.getApiSecret(),vi,AES_CBC);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("bizData", sign);
        paramMap.put("appId", apiInfoParam.getApiCode());



        log.info("【易车行】联登开始【queryUrl】{}【paramMap】{}", checkUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(checkUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【易车行】联登结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String message = resultObject.getString("message");

        loginResult.setCode(String.valueOf(code));
        loginResult.setMessage(message);
        loginResult.setResultInfo(result);
        loginResult.setParamInfo(JSON.toJSONString(paramMap));

        if (StrUtil.equals(String.valueOf(code), "200")) {
            JSONObject data = resultObject.getJSONObject("data");
                String url = data.getString("url");
                loginResult.setSuccess(true);
                loginResult.setLoginUrl(url);
        }
        return loginResult;
    }


    public static String encrypt(String text, String key, String iv, String mode){
        if (isEmpty(text) || isEmpty(key) || isEmpty(iv)) {
            return null;
        }

        try {
            // 创建AES加密器
            Cipher cipher = Cipher.getInstance(mode);

            SecretKeySpec secretKeySpec = getSecretKeySpec(key);

            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec(getBytes(iv)));

            // 加密字节数组
            byte[] encryptedBytes = cipher.doFinal(getBytes(text));

            // 将密文转换为 Base64 编码字符串
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    private static boolean isEmpty(Object str) {
        return null == str || "".equals(str);
    }
    private static byte[] getBytes(String str){
        if (isEmpty(str)) {
            return null;
        }

        try {
            return str.getBytes(StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    private static SecretKeySpec getSecretKeySpec(String key){
        SecretKeySpec secretKeySpec = new SecretKeySpec(getBytes(key), "AES");
        return secretKeySpec;
    }

}
